package importTable;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;

public class DumbPTYThead extends Thread {
    String cmd;
    String hostname;
    String userName;
    String password;

    public DumbPTYThead(String cmd, String hostname, String userName, String password) {
        this.cmd = cmd;
        this.hostname = hostname;
        this.userName = userName;
        this.password = password;
    }

    @Override
    public void run() {
        super.run();
        Connection conn = null;
        Session session = null;
        OutputStream out = null;
        boolean numFiles = false;
        String threadName = Thread.currentThread().getName();
        try {
            conn = new Connection(hostname);
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (conn.authenticateWithPassword(userName, password)) {
                System.out.println(Thread.currentThread().getName() + "创建连接成功!");
            } else {
                System.out.println("创建连接失败!");
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            session = conn.openSession();
            System.out.println(threadName + "打开session成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            session.execCommand(cmd);
        } catch (IOException e) {
            System.out.println("execCommand出错!");
            e.printStackTrace();
        }

        try {
            //InputStream in = session.getStdout();
            InputStream in = session.getStderr();
            InputStream stdout = new StreamGobbler(in);
            StringBuffer buffer = new StringBuffer();
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout, "UTF-8"));
                String line = null;
                FileWriter fw = new FileWriter(Thread.currentThread().getName() + ".txt");
                while ((line = br.readLine()) != null) {
                    buffer.append(line + "\n");
                    System.out.println(line);
                    fw.write(line + "\n");
                    fw.flush();
                }
                br.close();
                fw.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("退出循环....多线程不能关闭session.....");
            //session.close();
            //conn.close();
            //System.out.println(Thread.currentThread().getName()+"-> session和connection成功关闭");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
